<script setup lang="ts">
import { collectPageAPI } from '@/services/favorite'
import type { IFavoritePageParams } from '@/types/favorite'
import type { CategoryGoodItem } from '@/types/category'
import vkDataGoodsSkuPopupCenter from '@/components/vk-data-goods-sku-popup-center.vue'
import { onShow, onLoad, onReady } from '@dcloudio/uni-app'
import type { GoodsResult } from '@/types/goods'

import { ref } from 'vue'
import wucTab from '@/components/wuc-tab.vue'
import FlyInCart from '@/components/FlyInCart.vue'
import { useCart, useMemberStore } from '@/stores'
import type { IcartItem } from '@/types/cart'
const cartBasketRect = ref({})
const { addCartData, getCartTotalNum, removeCartData } = useCart()
const { getUserInfo } = useMemberStore()
const inCart: any = ref(null)
const initParams: IFavoritePageParams = {
  dateOrderBy: null,
  priceOrderBy: null,
  quantityOrderBy: null,
  page: 1,
  limit: 5,
  keyword: null,
  userId: getUserInfo().id,
}
const goodsInfo = ref({})
const isShowSku = ref(false)
const eventSpec: any = ref(null)

const noMore = ref(false)
const goodsList = ref<CategoryGoodItem[]>([])
const page = ref(1)
const limit = ref(5)
const total = ref(0)
const finish = ref(false)
const keyword = ref(null)

const showConfirm = ref(false)
const tabOptionList: any = ref([
  { name: '默认', sort: null, arrow: null },
  { name: '销量', sort: null, arrow: null },
  { name: '新品', sort: null, arrow: null },
  { name: '价格', sort: 'asc', arrow: true },
])
const tabOptionCur = ref(0)
const tabTagCur = ref(0)

const params = ref({ ...initParams } as IFavoritePageParams)
const onSearch = async (e: any) => {
  showConfirm.value = false
  params.value = {
    ...params.value,
    page: initParams.page,
    keyword: keyword.value,
  }
  goodsList.value = []
  await request()
}
const onClear = (e: any) => {
  showConfirm.value = true
  console.log(e)
}

const onFocus = (e: any) => {
  showConfirm.value = true
}

const tabOptionChange = async (index: any) => {
  tabOptionList.value = tabOptionList.value.map((item: any, i: number) => {
    if (i === index) {
      if (index === 0) {
        item.sort = null
        params.value = {
          ...params.value,
          dateOrderBy: null,
          priceOrderBy: null,
          quantityOrderBy: null,
        }
      }
      // 上架时间排序
      if (index === 1) {
        item.sort = 'desc'
        params.value = {
          ...params.value,
          dateOrderBy: null,
          priceOrderBy: null,
          quantityOrderBy: item.sort,
        }
      }
      // 上架时间排序
      if (index === 2 && i === 2) {
        item.sort = 'desc'
        params.value = {
          ...params.value,
          dateOrderBy: item.sort,
          priceOrderBy: null,
          quantityOrderBy: null,
        }
      }
      // 价格排序
      if (index === 3 && i === 3) {
        item.sort = item.sort === 'asc' ? 'desc' : 'asc'
        params.value = {
          ...params.value,
          dateOrderBy: null,
          quantityOrderBy: null,
          priceOrderBy: item.sort,
        }
      }
    } else {
      item.sort = null
    }
    return item
  })
  tabOptionCur.value = index

  params.value = {
    ...params.value,
    page: initParams.page,
  }
  goodsList.value = []
  await request()
}

const request = async () => {
  if (finish.value === true) {
    return
  }

  finish.value = true
  const res = await collectPageAPI({ ...params.value })
  goodsList.value = [...goodsList.value, ...res.data.list]
  total.value = res.data.total
  finish.value = false
}

// 滚动触底
const onScrolltolower = async () => {
  inCart.value?.addToCart()

  if (finish.value === true) {
    return
  }
  if (goodsList.value.length < total.value) {
    params.value.page = params.value.page + 1
  } else {
    noMore.value = true
    return
  }
  await request()
}

onLoad(async () => {
  uni.startPullDownRefresh()
  await request()
})

const triggered = ref(false) // 设置当前下拉刷新状态，true 表示下拉刷新已经被触发，false 表示下拉刷新未被触发

const onPulling = (e: any) => {
  if (e.detail.deltaY < 50) return // 防止上滑页面也触发下拉
  triggered.value = true
}
// 自定义下拉刷新被复位
const onRestore = () => {
  triggered.value = false
}
// 自定义下拉刷新被中止
const onAbort = () => {
  console.error('onAbort')
}

// 自定义下拉刷新被触发
const onRefresh = async () => {
  if (finish.value === true) {
    return
  }
  goodsList.value = []
  params.value = {
    ...params.value,
    ...initParams,
  }
  await request()
  triggered.value = false
}

const goToCart = () => {
  uni.switchTab({
    url: '/pages/cart/cart',
    success: () => {
      setCartTabBarBadge()
    },
  })
}

const setCartTabBarBadge = () => {
  const totalNum = getCartTotalNum()
  if (totalNum > 0) {
    uni
      .setTabBarBadge({
        index: 2,
        text: totalNum.toString(),
      })
      .catch((err) => {
        console.error('cart:', err)
      })
  } else {
    uni.removeTabBarBadge({
      index: 2,
    })
  }
}

const onSetmealOpenSkuPopup = (good: any, e: any) => {
  uni.navigateTo({
    url: `/pages/goods/setmealGoods?id=${good._id}`,
  })
}

const removeToCart = (good: GoodsResult) => {
  if (good['num'] && good['num'] > 0) {
    good['num'] = good.num - 1
    const skuId: number = good['sku_list'][0]['_id']

    // 加入购物车
    const cartRecord: IcartItem = {
      checked: true,
      id: good._id,
      goods_id: good._id,
      specification: '',
      name: good.name,
      image: good.imageUrl,
      description: good.description,
      price: good.price,
      costPrice: 0,
      num: good['num'],
      isSetmeal: 0,
      setmealPid: null,
      hasSku: 0,
      skuId,
    }
    console.log(cartRecord)
    removeCartData(cartRecord, true)
  }
}

const addToCartClick = (good: GoodsResult, e: any) => {
  good['num'] = (good.num || 0) + 1
  inCart.value.addToCart(e, good._id)
  const skuId: number = good['sku_list'][0]['_id']
  // 加入购物车
  const cartRecord: IcartItem = {
    checked: true,
    id: good._id,
    goods_id: good._id,
    specification: '',
    name: good.name,
    image: good.imageUrl,
    description: good.description,
    price: good.price,
    costPrice: 0, // goodsInfo.value.cost * setmealCartTotal.value,
    num: good['num'],
    isSetmeal: 0,
    setmealPid: null,
    hasSku: 0,
    skuId,
  }
  addCartData(cartRecord, true)
}

const onOpenSkuPopup = (good: any, e: any) => {
  eventSpec.value = e
  goodsInfo.value = good
  isShowSku.value = true
}
const onCloseSkuPopup = (ev: any) => {
  console.log('onCloseSkuPopup2', ev)
}

const addCart = async (ev: any) => {
  isShowSku.value = false
  let record: any = {}
  goodsList.value = goodsList.value.map((item: any, index: number) => {
    if (item._id === ev.goods_id) {
      inCart.value.addToCart(eventSpec.value, ev.goods_id)
      record = { ...item, num: ev.buy_num }
      return { ...item, num: ev.buy_num }
    }
    return item
  })

  // 加入购物车
  const cartRecord: IcartItem = {
    checked: true,
    id: ev._id,
    goods_id: record._id,
    name: ev.goods_name,
    image: ev.image,
    hasSku: record.hasSku,
    description: record.description,
    specification: ev.specification,
    price: ev.price,
    costPrice: ev.cost,
    num: ev.buy_num,
    isSetmeal: 0,
    setmealPid: null,
    skuId: ev._id,
  }
  console.log(cartRecord)
  addCartData(cartRecord, false)
}

// 页面加载完成事件
onReady(() => {
  let q = uni.createSelectorQuery()
  // 获取购物车位置
  setTimeout(() => {
    q.select('#cart')
      .boundingClientRect((data) => {
        cartBasketRect.value = data
      })
      .exec()
  }, 100)
})
</script>

<template>
  <view class="search-page">
    <FlyInCart ref="inCart" :cartBasketRect="cartBasketRect" />
    <view class="search-wrap">
      <uni-search-bar
        radius="30"
        class="search-bar"
        @confirm="onSearch"
        :focus="true"
        v-model="keyword"
        @blur="false"
        @focus="onFocus"
        @input="false"
        @cancel="false"
        cancelButton="none"
        @clear="onClear"
        placeholder="请输入搜索关键字"
        clearButton="always"
        bgColor="#f3f4f4"
        textColor="#666"
      >
        <template v-slot:searchIcon>
          <text class="iconfont icon-search"></text>
        </template>
      </uni-search-bar>
      <text class="confirm-btn" v-if="showConfirm" @click="onSearch">搜索</text>
    </view>
    <wuc-tab
      tabClass="option-tab"
      :tab-list="tabOptionList"
      :tabCur="tabOptionCur"
      @change="tabOptionChange"
    ></wuc-tab>

    <scroll-view
      class="search-main"
      scroll-y
      @scrolltolower="onScrolltolower"
      :refresher-enabled="true"
      :refresher-triggered="triggered"
      :refresher-threshold="100"
      refresher-background="#F5F5F7"
      @refresherpulling="onPulling"
      @refresherrefresh="onRefresh"
      @refresherrestore="onRestore"
      @refresherabort="onAbort"
      v-if="goodsList?.length"
    >
      <view class="search-list">
        <navigator
          :url="
            item.isSetmeal
              ? `/pages/goods/setmealGoods?id=${item._id}`
              : `/pages/goods/goods?id=${item._id}`
          "
          hover-class="none"
          class="search-item"
          v-for="item in goodsList"
          :key="item._id"
        >
          <image class="search-item-image" :src="item.goods_thumb" mode="scaleToFill" />
          <view class="search-item-content">
            <view class="title">{{ item.name }}</view>
            <view><rich-text class="con ellipsis" :nodes="item.description"></rich-text></view>
            <view class="spec-price">
              <view class="price">{{ item.price }}</view>

              <!-- 是否有规格，还是单品 -->
              <view class="bottom-right" @click.stop v-if="item.isSetmeal">
                <view class="spec setmeal" @click.stop="onSetmealOpenSkuPopup(item, $event)"
                  >选规格<text class="tag" v-if="item?.num">{{ item.num }}</text></view
                >
              </view>
              <view v-else-if="!item.isSetmeal && !item.hasSku" class="bottom-right" @click.stop>
                <template v-if="item?.num">
                  <view class="down" @click.stop="removeToCart(item)"></view>
                  <view class="number">
                    {{ item.num }}
                  </view>
                </template>
                <view class="up" @click.stop="addToCartClick(item, $event)"></view>
              </view>
              <view class="bottom-right" @click.stop v-else>
                <view class="spec setmeal" @click.stop="onOpenSkuPopup(item, $event)"
                  >选规格<text class="tag" v-if="item?.num">{{ item.num }}</text></view
                >
              </view>
            </view>
          </view>
        </navigator>
      </view>
      <view class="no-more" v-if="noMore && !finish">
        <text>已加载全部</text>
        <!-- <text class="relation">联系我们</text> -->
      </view>
    </scroll-view>
    <view v-else class="no-data search-main"><text>没有数据</text></view>

    <vk-data-goods-sku-popup-center
      ref="skuPopup"
      v-model="isShowSku"
      border-radius="20"
      :z-index="990"
      :localdata="goodsInfo"
      :mode="2"
      :amount-type="0"
      :stepBuyNum="0.5"
      :minBuyNum="0.5"
      theme="black-white"
      @close="onCloseSkuPopup"
      @add-cart="addCart"
    ></vk-data-goods-sku-popup-center>
    <view id="cart" class="cart-list" @click="goToCart">
      <text class="iconfont icon-cart-add"></text>
      <text class="tag" v-if="getCartTotalNum()">{{ getCartTotalNum() }}</text>
    </view>
  </view>
</template>

<style lang="scss">
@import '@/styles/variables.scss';

page {
  height: 100%;
  overflow: hidden;
  background-color: #fff;
}
.search-page {
  height: 100%;
  display: flex;
  flex-direction: column;

  height: 100%;
  display: flex;
  flex-direction: column;

  .cart-list {
    box-shadow: 0 10rpx 20rpx rgba(0, 0, 0, 0.2);
    position: fixed;
    bottom: 80rpx;
    left: 40rpx;
    background-color: #fff;
    border-radius: 50%;
    width: 80rpx;
    height: 80rpx;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    .tag {
      position: absolute;
      right: -10rpx;
      top: -10rpx;
      max-width: 60rpx;
      max-height: 30rpx;
      min-width: 30rpx;
      min-height: 30rpx;
      background-color: #fa5151;
      padding: 8rpx;
      border-radius: 50%;
      color: #fff;
      text-align: center;
      line-height: 30rpx;
      border: 1px solid #fff4ed;
      font-size: $font-small-size;
    }
  }

  .search-wrap {
    display: flex;
    flex-direction: row;
    align-items: center;
    .search-bar {
      flex: 1;
      .icon-search {
        font-size: $font-medium-size;
      }
      .uni-searchbar__box-search-input {
        margin: 0;
        padding: 0;
      }
      .uni-searchbar__box {
        height: 76rpx;
      }
      .uni-searchbar__box-search-input {
        font-size: $font-size;
      }
    }
    .confirm-btn {
      font-size: $font-size;
      color: #fff;
      background-color: $color;
      padding: 0 30rpx;
      line-height: 60rpx;
      border-radius: 30rpx;
      margin-right: 30rpx;
    }
  }

  .wuc-tab {
    .wuc-contanier-tab {
      .wuc-tab-item {
        margin: 20rpx 10rpx;
      }
    }

    &.option-tab {
      .wuc-contanier-tab {
        .wuc-tab-item {
          background-color: #f9fafb;
          font-size: $font-size;
          color: #4b5563;

          height: 62rpx;
          line-height: 62rpx;
          border-radius: 31rpx;

          &.cur {
            background-color: #f9fafb;
            font-size: $font-size;
            color: $color;
          }

          margin: 20rpx 10rpx;
        }
      }
    }
  }
  .search-main {
    flex: 1;
    /* 针对 H5 端 */
    ::-webkit-scrollbar {
      display: none; /* 隐藏滚动条 */
    }
    .search-list {
      padding: 0 $medium-padding;
      display: flex;
      flex-wrap: wrap; // 当空间不足时换行
      // gap: $smallx-padding; // 列之间的间距
      gap: $small-padding; // 列之间的间距

      .search-item {
        width: calc(50% - 15rpx);
        min-width: 0; // 确保即使内容超出宽度也能正确换行
        background-color: #fff;
        border-radius: $border-medium-radius;
        overflow: hidden;
        box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
        transition: transform 0.3s;
        border: 1px solid $border-color;

        .search-item-image {
          width: 100%;
          height: 346rpx;
          display: block;
        }

        .search-item-content {
          padding: 30rpx;

          .title {
            font-size: $font-medium-size;
            font-weight: $font-medium-weight;
            margin-bottom: 10rpx;
            color: $good-font-title-color;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .con {
            font-size: $font-size;
            color: $good-font-con-color;
            font-weight: $font-regular-weight;
            margin-bottom: 10rpx;
            display: block;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .price {
            font-size: $font-medium-size;
            font-weight: $font-medium-weight;
            color: #e53935;
          }
        }
      }
    }
  }
}
.no-more {
  display: flex;
  align-items: center;
  padding: 30rpx;
  justify-content: center;
  font-size: 22rpx;
  color: #c1c1c1;

  .relation {
    color: #2f5ad0;
  }
}

.spec-price {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

.bottom-right {
  margin-left: auto;
  display: flex;
  align-items: center;
  margin-top: auto;
  font-size: 18rpx;
  .spec {
    font-size: $font-size;
    color: $color;
    box-sizing: border-box;
    height: 48rpx;
    line-height: 1.66;
    border: 1px solid $color;
    padding: 0 20rpx;
    border-radius: 24rpx;
    position: relative;
    &.setmeal {
      background-color: $color;
      color: #fff;
    }
    .tag {
      position: absolute;
      right: -26rpx;
      top: -29rpx;
      max-width: 60rpx;
      max-height: 30rpx;
      min-width: 30rpx;
      min-height: 30rpx;
      background-color: #fa5151;
      padding: 8rpx;
      border-radius: 50%;
      color: #fff;
      text-align: center;
      line-height: 30rpx;
      border: 1px solid #fff4ed;
    }
  }
  .down {
    &::before {
      content: '\e619';
      font-family: 'iconfont' !important;
      font-size: 46rpx;
      color: $color;
    }
  }
  .up {
    &::before {
      content: '\e647';
      font-family: 'iconfont' !important;
      color: $color;
      font-size: 46rpx;
    }
  }
  .number {
    margin: 0 16rpx;
    font-size: $font-medium-size;
    font-weight: $font-medium-weight;
    color: $good-font-title-color;
  }
}
</style>
